package com.biscuit.page.basicservice.service;

import com.alibaba.fastjson.JSON;
import com.aliyun.dysmsapi20170525.Client;
import com.aliyun.dysmsapi20170525.models.SendSmsResponse;
import com.aliyun.teautil.models.RuntimeOptions;
import com.biscuit.page.basicservice.model.constant.AliyunConstant;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;

import java.util.HashMap;
import java.util.Map;

/**
 * @author biscuit
 * @create 2024年07月23日 21:03
 */
@Slf4j
@Service
public class AliyunService {

    // 发送短信验证码
    public SendSmsResponse noteVerifyCodePublish(String mobile, String verifyCode) throws Exception {
        try {
            // 创建请求客户端，用于阿里云发送请求
            com.aliyun.teaopenapi.models.Config config = new com.aliyun.teaopenapi.models.Config()
                    .setAccessKeyId(AliyunConstant.ACCESS_KEY_ID)
                    .setAccessKeySecret(AliyunConstant.ACCESS_KEY_SECRET);
            config.endpoint = "dysmsapi.aliyuncs.com";
            Client client = new Client(config);

            // 发送短信验证码请求参数
            Map<String, String> templateParamMap = new HashMap<>();
            templateParamMap.put("code", verifyCode);
            com.aliyun.dysmsapi20170525.models.SendSmsRequest clientRequest = new com.aliyun.dysmsapi20170525.models.SendSmsRequest()
                    .setPhoneNumbers(mobile)
                    .setTemplateCode("SMS_470220104")
                    .setTemplateParam(JSON.toJSONString(templateParamMap))
                    .setSignName("饼干标签页");

            // 请求阿里云向指定手机号发送验证码
            return client.sendSmsWithOptions(clientRequest, new RuntimeOptions());

        } catch (Exception e) {
            log.error("AliyunService noteVerifyCodePublish 阿里云短信验证码发送失败，error => {}", JSON.toJSONString(e));
            throw e;
        }
    }

}
